home *** CD-ROM | disk | FTP | other *** search
/ Aminet 40 / Aminet 40 (2000)(Schatztruhe)[!][Dec 2000].iso / Aminet / dev / lang / Python16_Src.lha / Python16_Source / Python / getcwd.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-08-03  |  1.3 KB  |  83 lines

  1. /* Two PD getcwd() implementations.
  2.    Author: Guido van Rossum, CWI Amsterdam, Jan 1991, <guido@cwi.nl>. */
  3.  
  4. #include <stdio.h>
  5. #include <errno.h>
  6.  
  7. #ifdef HAVE_GETWD
  8.  
  9. /* Version for BSD systems -- use getwd() */
  10.  
  11. #ifdef HAVE_SYS_PARAM_H
  12. #include <sys/param.h>
  13. #endif
  14.  
  15. #ifndef MAXPATHLEN
  16. #define MAXPATHLEN 1024
  17. #endif
  18.  
  19. extern char *getwd();
  20.  
  21. char *
  22. getcwd(buf, size)
  23.     char *buf;
  24.     int size;
  25. {
  26.     char localbuf[MAXPATHLEN+1];
  27.     char *ret;
  28.     
  29.     if (size <= 0) {
  30.         errno = EINVAL;
  31.         return NULL;
  32.     }
  33.     ret = getwd(localbuf);
  34.     if (ret != NULL && strlen(localbuf) >= size) {
  35.         errno = ERANGE;
  36.         return NULL;
  37.     }
  38.     if (ret == NULL) {
  39.         errno = EACCES; /* Most likely error */
  40.         return NULL;
  41.     }
  42.     strncpy(buf, localbuf, size);
  43.     return buf;
  44. }
  45.  
  46. #else /* !HAVE_GETWD */
  47.  
  48. /* Version for really old UNIX systems -- use pipe from pwd */
  49.  
  50. #ifndef PWD_CMD
  51. #define PWD_CMD "/bin/pwd"
  52. #endif
  53.  
  54. char *
  55. getcwd(buf, size)
  56.     char *buf;
  57.     int size;
  58. {
  59.     FILE *fp;
  60.     char *p;
  61.     int sts;
  62.     if (size <= 0) {
  63.         errno = EINVAL;
  64.         return NULL;
  65.     }
  66.     if ((fp = popen(PWD_CMD, "r")) == NULL)
  67.         return NULL;
  68.     if (fgets(buf, size, fp) == NULL || (sts = pclose(fp)) != 0) {
  69.         errno = EACCES; /* Most likely error */
  70.         return NULL;
  71.     }
  72.     for (p = buf; *p != '\n'; p++) {
  73.         if (*p == '\0') {
  74.             errno = ERANGE;
  75.             return NULL;
  76.         }
  77.     }
  78.     *p = '\0';
  79.     return buf;
  80. }
  81.  
  82. #endif /* !HAVE_GETWD */
  83.